package co.th.helper.dao;

import java.math.BigDecimal;
import java.util.List;

import co.th.helper.jdbc.JdbcTemplate;
import co.th.helper.jdbc.mapper.BrandRowMapper;
import co.th.helper.model.Brand;

public class DepartmentDAO extends JdbcTemplate<Brand>{

	public List<Brand> getAll() {
		try {
			String sql = "select * from brand";
			JdbcTemplate<Brand> jdbcTemplate = new JdbcTemplate<Brand>();
			List<Brand> list = jdbcTemplate.queryList(sql, null, new BrandRowMapper());
			return list;
		} catch (Exception e) {
			throw new RuntimeException("Cat not get all person");
		}
	}
	
	public synchronized Brand save(Brand brand){
		try {
			brand.setBrandCode(genBrandCode());
			
			String sql = "INSERT INTO brand (brand_code, brand_name_th, brand_name_en, create_by, create_date, update_by, update_date) VALUES ( ?, ?, ?, ?, ?, ?, ?);";
			Object[] params = new Object[7];
			params[0] = brand.getBrandCode();
			params[1] = brand.getBrandNameTh();
			params[2] = brand.getBrandNameEn();
			params[3] = brand.getCreateBy();
			params[4] = brand.getCreateDate();
			params[5] = brand.getUpdateBy();
			params[6] = brand.getUpdateDate();
			this.saveUnique(sql, params);
			return brand;
		} catch (Exception e) {
			throw new RuntimeException("Cat not get all person");
		}
	}
	
	private BigDecimal genBrandCode() throws Exception{
		String sql = "select max(brand_code) AS brand_code from brand";
		JdbcTemplate<Brand> jdbcTemplate = new JdbcTemplate<Brand>();
		Brand objRow = jdbcTemplate.queryUnique(sql, null, new BrandRowMapper());
		return BigDecimal.valueOf(objRow.getBrandCode().intValue() + 1);
	}
}
